<template>
    <div>
        <el-form :model="spuForm" label-width="100px">
            <el-form-item label="spu名称">
                <el-input v-model="spuForm.spuName" placeholder="请你输入spu名称" />
            </el-form-item>
            <el-form-item label="spu品牌">
                <el-select v-model="spuForm.tmId" placeholder="请你选择品牌">
                    <el-option v-for="(item, _index) in allTrademarkList" :label="item.tmName" :value="item.id"
                        :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="spu描述">
                <el-input v-model="spuForm.description" type="textarea" placeholder="请你输入描述" />
            </el-form-item>
            <el-form-item label="spu照片">
                <!-- <el-input v-model="spuForm.spuImageList" /> -->
                <el-upload v-model:file-list="imageList" action="/api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="spu销售属性">
                <!-- <el-input v-model="spuForm.spuSaleAttrList" /> -->

                <el-select v-model="saleAttrIdAndValueName"
                    :placeholder="unSelectSaleAttrList.length ? `还未选择${unSelectSaleAttrList.length}个` : '无'">
                    <el-option v-for="(item, _index) in unSelectSaleAttrList" :label="item.name"
                        :value="`${item.id}:${item.name}`" :key="item.id"></el-option>
                </el-select>

                <el-button type="primary" style="margin-left: 10px;" icon="Plus"
                    :disabled="saleAttrIdAndValueName ? false : true" @click="addSaleAtrr">添加属性</el-button>
                <el-table :data="spuForm.spuSaleAttrList" border style="width: 100%;margin: 10px 0px">
                    <el-table-column label="序号" type="index" width="150" />
                    <el-table-column prop="saleAttrName" label="属性名" width="150px" />
                    <el-table-column prop="prop" label="属性值名称列表">
                        <template #default="{ row }">
                            <el-tag style="margin: 0px 5px" @close="row.spuSaleAttrValueList.splice(index, 1)"
                                v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id" class="mx-1" closable
                                :type="item.type">
                                {{ item.saleAttrValueName }}
                            </el-tag>
                            <el-input v-if="row.flag == true" @blur="toLook(row)" v-model="row.saleAttrValue"
                                placeholder="请输入标签名称" size="small" style="width:150px;margin: 0px 5px;"></el-input>
                            <el-button v-else type="primary" icon="Plus" size="small" @click="toEdit(row)"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="150px">
                        <template #default="{ $index }">
                            <el-button type="primary" icon="Delete" size="small"
                                @click="spuForm.spuSaleAttrList?.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </el-form-item>

        </el-form>
        <el-button type="primary" size="default" :disabled="saleAttrEmpty" @click="save">保存</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </div>
</template>

<script setup lang="ts">

import { SpuData, AllTradeMark, SpuHasImg, SaleAttrResponseData, HasSaleAttrResponseData, Trademark, HasSaleAttr, SpuImg, SaleAttr, SaleAttrValue } from '@/api/product/spu/type';
// import { reqGetTrademarkList } from '@/api/product/trademark';
// import {  TrademarkListResponseData } from '@/api/product/trademark/type';
import { onMounted, ref, computed } from 'vue'
import { reqAllTradeMark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu';
import { ElMessage } from 'element-plus';
// 父组件传过的方法
let $emit = defineEmits(['changeScene'])

// 全部的品牌
let allTrademarkList = ref<Trademark[]>([])

// 全部的销售属性
let allSaleAttrList = ref<HasSaleAttr[]>([])

const cancel = () => {
    $emit('changeScene', {flag:0,params:spuForm.value.id?'update':'add'})
}
onMounted(async () => {
    // let result: TrademarkListResponseData = await reqGetTrademarkList();
    // trademarkList.value = result.data
})

const spuForm = ref<SpuData>({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: []
})

const imageList = ref<SpuImg[]>([])



const initHasSpuData = async (spu: SpuData) => {

    Object.assign(spuForm.value, spu)


    // 获取全部品牌的数据
    let allTradeMark: AllTradeMark = await reqAllTradeMark();
    if (allTradeMark.code === 200) {
        allTrademarkList.value = allTradeMark.data
    }
    // SPU已有的照片
    let spuImageList: SpuHasImg = await reqSpuImageList((spu.id as number));
    if (spuImageList.code === 200) {
        // spuForm.value.spuImageList = spuImageList.data
        imageList.value = spuImageList.data.map(item => {
            return {
                name: item.imgName,
                url: item.imgUrl
            }
        })
    }

    let spuHasSaleAttr: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
    if (spuHasSaleAttr.code === 200) {
        spuForm.value.spuSaleAttrList = spuHasSaleAttr.data
    }

    let allSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr()
    if (allSaleAttr.code === 200) {
        allSaleAttrList.value = allSaleAttr.data
    }

}
let dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref<string>('')
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true

}

const handleRemove = () => {
    // console.info(123)
    // 删除照片墙的图片
}

const handlerUpload = (file: any) => {
    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif') {
        if (file.size < 1024 * 1024 * 3) {
            return true
        } else {
            ElMessage.error('上传图片大小不能超过3M')
            return false
        }
    } else {
        ElMessage.error('上传图片格式为jpeg|png|gif')
        return false

    }


}
let unSelectSaleAttrList = computed(() => {
    return allSaleAttrList.value.filter(item => {
        // 数组的every方法，判断数组中每一项是否都满足条件。
        // 只有有一个不满足条件，就返回false
        // 只有每一项都满足条件，才返回true
        // 此处item不等于所有的itme2.saleAttrName才会返回true
        return spuForm.value.spuSaleAttrList?.every(itme2 => {
            return itme2.saleAttrName !== item.name;
        })
    })
})

let saleAttrIdAndValueName = ref<String>('')

const addSaleAtrr = () => {
    // 判断saleAttrIdAndValueName是否为空
    let [saleAttrId, name] = saleAttrIdAndValueName.value.split(':')
    spuForm.value.spuSaleAttrList?.push({
        saleAttrName: name,
        baseSaleAttrId: saleAttrId,
        spuSaleAttrValueList: []
    })
    saleAttrIdAndValueName.value = ''

}

const toEdit = (row: SaleAttr) => {
    // 点击按钮的时候，input组件显示
    row.flag = true;
    row.saleAttrValue = ''
}
const toLook = (row: SaleAttr) => {
    // 点击按钮的时候，input组件显示

    let newSaleAttrValue: SaleAttrValue = {
        "saleAttrValueName": (row.saleAttrValue as string),
        "saleAttrName": row.saleAttrName,
        "baseSaleAttrId": row.baseSaleAttrId
    }

    // 参数校验
    if (newSaleAttrValue.saleAttrValueName.trim() === '') {
        ElMessage.error('销售属性值不能为空')
        return
    }

    // 判断是否重复
    let isRepeat = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === newSaleAttrValue.saleAttrValueName
    })
    if (isRepeat) {
        ElMessage.error('销售属性值不能重复')
        return
    }
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}

const save = async () => {

    spuForm.value.spuImageList = imageList.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    let result = await reqAddOrUpdateSpu(spuForm.value)
    if (result.code === 200) {
        ElMessage.success(spuForm.value.id ? '更新成功' : '保存成功')
        $emit('changeScene', {flag:0,params:spuForm.value.id?'update':'add'})
        // 关闭对话框
        // spuForm.value.dialogFormVisible = false
        // 刷新列表
        // getSpuList()
    } else {
        ElMessage.error(spuForm.value.id ? '更新失败' : '保存失败')
    }
}

let saleAttrEmpty = computed(() => {
    return spuForm.value.spuSaleAttrList?.length === 0 ? true : false
})

const initAddSpu = async (c3Id: number | string) => {
    imageList.value = []
    Object.assign(spuForm.value, {
        category3Id: '',
        spuName: '',
        description: '',
        tmId: '',
        spuImageList: [],
        spuSaleAttrList: []
    })

    spuForm.value.category3Id = c3Id
    saleAttrIdAndValueName.value = ''
  


    // alert('addspu')
    // 获取全部品牌的数据
    let allTradeMark: AllTradeMark = await reqAllTradeMark();
    if (allTradeMark.code === 200) {
        allTrademarkList.value = allTradeMark.data
    }


    let allSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr()
    if (allSaleAttr.code === 200) {
        allSaleAttrList.value = allSaleAttr.data
    }



}

// 暴露方法，让父组件调用
defineExpose({ initHasSpuData, initAddSpu })
</script>
<script  lang="ts">
export default {
    name: 'SpuForm'
}
</script>
<style scoped></style>